/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.swak.netty.echo;

import com.swak.utils.Fmt;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;

/**
 * Handler implementation for the echo client.  It initiates the ping-pong
 * traffic between the echo client and server by sending the first message to
 * the server.
 */
public class EchoClientHandler extends ChannelDuplexHandler {

	private final ByteBuf firstMessage;

	/**
	 * Creates a client-side handler.
	 */
	public EchoClientHandler() {
		firstMessage = Unpooled.buffer(EchoClient.SIZE);
		for (int i = 0; i < firstMessage.capacity(); i++) {
			firstMessage.writeByte((byte) i);
		}
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		// ctx.channel().writeAndFlush(firstMessage);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
		// ctx.write(msg);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) {
		// ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		// Close the connection when an exception is raised.
		Fmt.out.println("发送数据异常： " + cause);
	}

	@Override
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		if (msg instanceof String) {
			ByteBuf byteBuf = ctx.channel().alloc().buffer();
			Fmt.out.println("编码数据:" + msg);
			byteBuf.writeBytes(((String) msg).getBytes());

			// 模拟一个异常
			// 这里会触发 in 方向的 下一个来处理这个异常（注意：而不是 out 方向的下一个，也不是当前）
			// 所有不用这种方式
//			try {
//				int i = 1 / 0;
//				Fmt.out.println(i);
//			} catch (Exception e) {
//				ctx.fireExceptionCaught(e);
//			}

			// 模拟一个异常, 测试写超时
			// Thread.sleep(10000);

			// 模拟一个异常
			// 这种异常不会被 出站捕获
			int i = 1 / 0;
			Fmt.out.println(i);
			ctx.write(byteBuf, promise);
		} else {
			ctx.write(msg, promise);
		}
	}

	@Override
	public void flush(ChannelHandlerContext ctx) throws Exception {
		super.flush(ctx);
	}
}
